/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package org.fh.itsbankomat.businesslogic;

import java.math.BigDecimal;
import javax.ejb.Singleton;
import javax.ejb.LocalBean;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.fh.itsbankomat.businesslogic.model.Bankomatkarte;
import org.fh.itsbankomat.businesslogic.model.Transaktionen;


/**
 *
 * @author MeinLaptop
 */
@Singleton
@LocalBean
public class Bankomat {
     @PersistenceContext
    private EntityManager m_Em;

    
    private Transaktionen m_ActiveTransaction = null;
    private double m_dMoneyStorage = 10000;

    public Transaktionen insertCard(Bankomatkarte v_Card) {
        if(m_ActiveTransaction != null){
            Transaktionen errorT = new Transaktionen();
            errorT.setMessage("Illegaler Zustand -Transaktion bereits aktiv, bitte warten, bis diesee beendet wurde!");
            errorT.setMessageid(MessageIDs.ERROR.toString());
            return errorT;
        }
        
        m_ActiveTransaction = new Transaktionen();
        m_ActiveTransaction.setIban(v_Card.getBankomatkartePK().getIban());
        m_ActiveTransaction.setStatus(TransaktionStates.CARD_INSERTED.getStateAsString());
        
        m_Em.persist(m_ActiveTransaction);
        
        
        return m_ActiveTransaction;
    }

    public Transaktionen setPIN(String v_PIN){
        return m_ActiveTransaction;
    }
    
    public Transaktionen setAmount(double v_dAmount){
        if((m_dMoneyStorage - v_dAmount)<0){
            m_ActiveTransaction.setMessage("Geldmenge nicht verfügbar!");
            m_ActiveTransaction.setMessageid(MessageIDs.WARN.toString());
        } else {
            m_ActiveTransaction.setBetrag(new BigDecimal(v_dAmount));
            m_ActiveTransaction.setMessageid(MessageIDs.OK.toString());
        }
        return m_ActiveTransaction;
    }
    
    public Transaktionen takeCard(){
        m_ActiveTransaction.setStatus(TransaktionStates.CARD_PULLED.getStateAsString());
        
        return m_ActiveTransaction;
    }
    
    public Transaktionen takeMoney(){
        m_dMoneyStorage -= m_ActiveTransaction.getBetrag().doubleValue();
        m_ActiveTransaction.setStatus(TransaktionStates.END.getStateAsString());
        m_ActiveTransaction = null;
        
        return m_ActiveTransaction;
    } 
    
    
    // ------------------------ external by bank officer -----------------
    
    public void changeMoneyStorage(double v_dAmount){
        m_dMoneyStorage = Math.max(0.0, m_dMoneyStorage + v_dAmount);
    }
}
